package com.hepinghospital.user.ui.fragment;

import android.annotation.SuppressLint;
import android.graphics.Color;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.TextView;

import androidx.appcompat.app.AlertDialog;
import androidx.constraintlayout.widget.ConstraintLayout;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.hepinghospital.user.R;
import com.hepinghospital.user.base.BaseApplication;
import com.hepinghospital.user.base.BaseFragment;
import com.hepinghospital.user.eventbus.WebSocket;
import com.hepinghospital.user.eventbus.WebSocketWrapper;
import com.hepinghospital.user.ui.activity.consult.ChatActivity;
import com.hepinghospital.user.ui.activity.consult.JiuZhenAddFragment;
import com.hepinghospital.user.ui.activity.consult.JiuZhenFragment;
import com.hepinghospital.user.ui.activity.home.SearchDoctorActivity;
import com.hepinghospital.user.util.ImageLoaderHelper;
import com.hepinghospital.user.util.ToastUtil;
import com.rest.business.RestProxy;
import com.rest.observer.BaseObserver;
import com.rest.response.ChatResponse;
import com.rest.response.IMListResponse;
import com.scwang.smartrefresh.layout.SmartRefreshLayout;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;
import org.jetbrains.annotations.NotNull;

import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.OnClick;
import io.reactivex.Observer;
import io.reactivex.disposables.Disposable;
import jz.joyoung.robot.util.UIConstants;
import jz.joyoung.robot.util.UtilList;

/**
 * 就诊室-图文问诊
 *
 * @author Administrator
 * @date 2018/5/28
 */

public class IMFragment extends BaseFragment {
    @BindView(R.id.refreshLayout)
    SmartRefreshLayout refreshLayout;
    @BindView(R.id.recyclerView)
    RecyclerView recyclerView;
    @BindView(R.id.cl_empty)
    ConstraintLayout clEmpty;

    private MyAdapter adapter;
    List<IMListResponse.IMItem> list = new ArrayList<>();

    @SuppressLint("StaticFieldLeak")
    private static IMFragment imFragment;

    public static IMFragment newInstance() {
        if (imFragment == null) {
            imFragment = new IMFragment();
        }
        return imFragment;
    }

    @Override
    protected int getLayoutResource() {
        return R.layout.fragment_im;
    }

    @Override
    protected void initView() {
        LinearLayoutManager manager = new LinearLayoutManager(getActivity());
        manager.setOrientation(LinearLayoutManager.VERTICAL);
        recyclerView.setLayoutManager(manager);
        adapter = new MyAdapter();
        recyclerView.setAdapter(adapter);
        refreshLayout.setEnableLoadMore(false);
        refreshLayout.setOnRefreshListener(refreshlayout -> queryIMList(UIConstants.JIUZHEN_QUERY_TYPE_0));
    }

    @Override
    protected void initData() {
        if (!EventBus.getDefault().isRegistered(this)) {
            EventBus.getDefault().register(this);
        }
    }

    @OnClick({R.id.btn_appoint, R.id.iv_empty})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.btn_appoint:
            case R.id.iv_empty:
                Bundle bundle = new Bundle();
                bundle.putInt("type", 1);
                startActivity(SearchDoctorActivity.class, bundle);
//                startActivity(BookDoctor2Activity.class, bundle);
                break;
            default:
                break;
        }
    }


    class MyAdapter extends RecyclerView.Adapter<MyAdapter.Holder> {

        @NotNull
        @Override
        public Holder onCreateViewHolder(@NotNull ViewGroup parent, int viewType) {
            Holder myHolder;
            myHolder = new Holder(LayoutInflater.from(getActivity()).inflate(R.layout.item_im, parent, false));
            return myHolder;
        }

        @SuppressLint("SetTextI18n")
        @Override
        public void onBindViewHolder(Holder holder, final int position) {
            holder.itemView.setOnClickListener(v -> {
                Bundle bundle = new Bundle();
                bundle.putSerializable("obj", list.get(position));
                startActivity(ChatActivity.class, bundle);
            });
            holder.itemView.setOnLongClickListener(v -> {
                if (list.get(position).doctorIsTop == 0) {
                    new AlertDialog.Builder(mContext).setTitle("置顶")
                            .setMessage("是否置顶该聊天")
                            .setPositiveButton("确定", (dialog, which) -> {
                                // 显示授权界面
                                updateTop(list.get(position).diagnoseId, 1 + "");
                            })
                            .setNegativeButton("取消", null).show();
                } else {
                    new AlertDialog.Builder(mContext).setTitle("置顶")
                            .setMessage("是否取消置顶该聊天")
                            .setPositiveButton("确定", (dialog, which) -> {
                                // 显示授权界面
                                updateTop(list.get(position).diagnoseId, 0 + "");
                            })
                            .setNegativeButton("取消", null).show();
                }
                return false;
            });
            if (list.get(position).doctorIsTop == 1) {
                holder.itemView.setBackgroundColor(Color.parseColor("#0F55B8A9"));
            } else {
                holder.itemView.setBackgroundColor(getResources().getColor(R.color.white));
            }
            holder.tv_name.setText(list.get(position).doctorName);
            holder.tv_department.setText(list.get(position).deptName);

            if (list.get(position).businessType == UIConstants.GRAPHIC_TYPE_1) {
                holder.tv_consult_type.setText(R.string.string_consult);
//                holder.tv_consult_type.setBackgroundColor(getResources().getColor(R.color.color_grey_button_normal));

            } else if (list.get(position).businessType == UIConstants.GRAPHIC_TYPE_2) {
                holder.tv_consult_type.setText(R.string.string_referral);
//                holder.tv_consult_type.setBackgroundColor(getResources().getColor(R.color.chooser_orange));
            }

            if (list.get(position).messageType == ChatResponse.TEXT) {
                holder.tv_message.setText(list.get(position).content);
            } else if (list.get(position).messageType == ChatResponse.IMAGE) {
                holder.tv_message.setText("[图片]");
            } else if (list.get(position).messageType == ChatResponse.PRESCRIPTION) {
                holder.tv_message.setText("[处方]");
            } else if (list.get(position).messageType == ChatResponse.AUDIO) {
                holder.tv_message.setText("[语音]");
            } else if (list.get(position).messageType == -1) {
                holder.tv_message.setText("");
            } else if (list.get(position).messageType == ChatResponse.CHECKOUT) {
                holder.tv_message.setText("[检查检验]");
            }
            holder.tv_time.setText(list.get(position).sendTime);
            if (list.get(position).unreadCount != 0) {
                holder.tv_unreadCount.setVisibility(View.VISIBLE);
                holder.tv_unreadCount.setText(list.get(position).unreadCount + "");
            } else {
                holder.tv_unreadCount.setVisibility(View.GONE);
            }
            ImageLoaderHelper.getInstance().GlideCircleImageLoader(mContext, list.get(position).picture, holder.img_head);
        }

        @Override
        public int getItemCount() {
            return list.size();
        }

        class Holder extends RecyclerView.ViewHolder {

            TextView tv_name, tv_department, tv_message, tv_time, tv_unreadCount, tv_consult_type;
            ImageView img_head;

            public Holder(View itemView) {
                super(itemView);
                tv_name = itemView.findViewById(R.id.tv_name);
                tv_unreadCount = itemView.findViewById(R.id.tv_unreadCount);
                tv_time = itemView.findViewById(R.id.tv_time);
                tv_department = itemView.findViewById(R.id.tv_department);
                tv_consult_type = itemView.findViewById(R.id.tv_consult_type);
                tv_message = itemView.findViewById(R.id.tv_message);
                img_head = itemView.findViewById(R.id.img_head);
            }
        }
    }


    public void queryIMList(int queryType) {
        RestProxy.getInstance().queryIMList(BaseApplication.currentUserId, new Observer<IMListResponse>() {
            @Override
            public void onSubscribe(Disposable d) {

            }

            @Override
            public void onNext(IMListResponse imListResponse) {

                if (queryType == UIConstants.JIUZHEN_QUERY_TYPE_1) {
                    if (imListResponse.records != null && imListResponse.records.size() > 0) {
                        JiuZhenAddFragment.newInstance().getDoctorFragmentAdapter().setPageTitle(UIConstants.JIUZHEN_TAB_POSITION_0, imListResponse.records.size());
                        JiuZhenAddFragment.newInstance().jumpToPage(0);
                    } else {
                        JiuZhenAddFragment.newInstance().getDoctorFragmentAdapter().setPageTitle(UIConstants.JIUZHEN_TAB_POSITION_0, 0);
                    }
                } else {
                    if (!UtilList.isEmpty(imListResponse.records)) {
                        if (refreshLayout != null) {
                            refreshLayout.setVisibility(View.VISIBLE);
                        }
                        if (clEmpty != null) {
                            clEmpty.setVisibility(View.GONE);
                        }
                        list.clear();
                        list.addAll(imListResponse.records);
                        adapter.notifyDataSetChanged();
                    } else {
                        if (refreshLayout != null) {
                            refreshLayout.setVisibility(View.GONE);

                        }
                        if (clEmpty != null) {
                            clEmpty.setVisibility(View.VISIBLE);
                        }
                    }
                }
            }

            @Override
            public void onError(Throwable e) {
                e.printStackTrace();
                refreshLayout.finishRefresh(false);
                ToastUtil.onError(mContext, e);
            }

            @Override
            public void onComplete() {
                refreshLayout.finishRefresh(true);
            }
        });
    }

    @Override
    public void onResume() {
        super.onResume();
        queryIMList(UIConstants.JIUZHEN_QUERY_TYPE_0);

    }

    @Override
    public void setUserVisibleHint(boolean isVisibleToUser) {
        super.setUserVisibleHint(isVisibleToUser);
        if (getUserVisibleHint()) {
            queryIMList(UIConstants.JIUZHEN_QUERY_TYPE_0);
        }
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        if (EventBus.getDefault().isRegistered(this)) {
            EventBus.getDefault().unregister(this);
        }
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onMessageEvent(WebSocket webSocket) {
        if (webSocket.eventFlag == 0) {
            queryIMList(UIConstants.JIUZHEN_QUERY_TYPE_0);
        }
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onMessageEvent2(WebSocketWrapper webSocket) {
        if (webSocket.cmd == UIConstants.WEBSOCKET_CMD_109 || webSocket.cmd == UIConstants.WEBSOCKET_CMD_101 || webSocket.cmd == UIConstants.WEBSOCKET_CMD_110) {
            queryIMList(UIConstants.JIUZHEN_QUERY_TYPE_0);
        }
    }

    private void updateTop(String diagnoseId, String status) {
        RestProxy.getInstance().updateTop(diagnoseId, status, new BaseObserver<String>() {
            @Override
            public void onSuccess(String s) {
                queryIMList(UIConstants.JIUZHEN_QUERY_TYPE_0);
            }
        });
    }
}
